package com.tongzhan.service;

import com.tongzhan.base.BaseCriteria;
import com.tongzhan.base.BaseShareService;
import com.tongzhan.entity.xiangxian.Brand;
import com.tongzhan.repository.BrandRepository;
import com.tongzhan.utils.ThreadLocalUtil;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author gyjw
 * @date 2020/10/16
 */
@Service
public class BrandService extends BaseShareService {

    @Autowired
    private BrandRepository brandRepository;

    public long addbarnd(Brand brand) {
        brand.setType(0);//统战部
        brand.setIs_del(0);
        brand.setTime(new Date());
        //设置街道社区
        brand.setStreetCode(ThreadLocalUtil.getThreadLocal().getStreetCode());
        brand.setVillageCode(ThreadLocalUtil.getThreadLocal().getVillageCode());
        long l = brandRepository.insertSelective(brand);
        if (l > 0) {
            return 1;
        }
        return 0;
    }


    public Brand brandDetail(String bid) {
        Brand brand = brandRepository.findByPrimaryKey(bid);
        return brand;
    }

    public Page<Brand> brandList(String name, Integer page, Integer size) {
        Query query = new Query(BaseCriteria.where("is_del").is(0).and("type").is(0));
        //查询条件
        if (ThreadLocalUtil.getThreadLocal().getDutiesCode().equals(ThreadLocalUtil.STREET_CODE)) {
            query.addCriteria(BaseCriteria.where("streetCode").like(ThreadLocalUtil.getThreadLocal().getStreetCode()));
        }
        if (ThreadLocalUtil.getThreadLocal().getDutiesCode().equals(ThreadLocalUtil.VILLAGE_CODE)) {
            query.addCriteria(BaseCriteria.where("villageCode").like(ThreadLocalUtil.getThreadLocal().getVillageCode()));
        }
        if (Strings.isNotBlank(name)) {
            query.addCriteria(BaseCriteria.where("name").like(name));
        }
        PageRequest of = PageRequest.of(page, size, Sort.Direction.DESC, "time");
        Page<Brand> all = brandRepository.findPage(query, of);
        return all;
    }

    public long findBrandByName(String name) {
        long l = brandRepository.count(new Query().addCriteria(BaseCriteria.where("is_del").is(0).and("name").is(name)));
        return l;
    }

}
